package agile.tools

import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Map;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

//import flexjson.JSONSerializer;

class TestSaver {
	Mongo mongo;
	DB db;
	DBCollection coll;
	
	public void connectToDatabase() throws UnknownHostException, MongoException {
		mongo = new Mongo("flame.mongohq.com", 27062);
		DB db = mongo.getDB( "trial" );
		db.authenticate("admin", "admin".toCharArray());
		coll = db.getCollection("testCollection");
	}
	
	public void printAllObjectsInDb() {
		DBCursor cursor = coll.find();
		while(cursor.hasNext()) {
            DBObject myDoc = cursor.next();
            Map docMap = myDoc.toMap();
            Iterator iter = docMap.keySet().iterator();
            while(iter.hasNext()) {
            	Object id = (Object) iter.next();
            	System.out.println(id);
//            	String newjson = (String) myDoc.get(key.toString());
//                Person p2 = (Person) new JSONDeserializer().deserialize(newjson);
//                System.out.println(key + " ------> " + p2);
            }
        }
	}
	
	public void addPersonToDb(Person person) {
		BasicDBObject doc = new BasicDBObject();
//        doc.put("somemethod", new JSONSerializer().serialize(person));
//        coll.insert(doc);
        System.out.println("person added to database");
	}
	
	public static void main(String[] args) throws UnknownHostException, MongoException {
		TestSaver d = new TestSaver();
		d.connectToDatabase();
		d.printAllObjectsInDb();
		
//		d.addPersonToDb(new Person());
//		d.printAllObjectsInDb();
//		
//		Person p = new Person();
//		p.setFirstName("qwerty");
//		d.addPersonToDb(p);
//		d.printAllObjectsInDb();
	}
//		Person p = new Person();
//		
//		JSONSerializer serializer = new JSONSerializer();
//        String json = serializer.serialize( p );
//        System.out.println(json);
//        json = json.replace("Ayan", "Ankit");
//        json = json.replace("OH", "FL");
//        System.out.println(json);
//        Person p1 = (Person) new JSONDeserializer().deserialize(json);
//        System.out.println(p);
//        System.out.println(p1);
//        
//        Mongo m = new Mongo( "localhost" );
//        DB db = m.getDB( "mydb" );
//        DBCollection coll = db.getCollection("testCollection");
//        
//        BasicDBObject doc = new BasicDBObject();
//        doc.put("somemethod", json);
//        coll.insert(doc);
//        System.out.println("document inserted");
//        
//        DBCursor cur = coll.find();
//
//        while(cur.hasNext()) {
//            DBObject myDoc = cur.next();
//            String newjson = (String) myDoc.get("somemethod");
//            Person p2 = (Person) new JSONDeserializer().deserialize(newjson);
//            System.out.println(p2);
//        }
//	}
}